import 'dart:convert';
import 'dart:typed_data';

import 'package:dio/dio.dart';
import 'package:enterprise_v6_app/app/components/toast_widget.dart';
import 'package:enterprise_v6_app/app/core/core.dart';
import 'package:enterprise_v6_app/app/core/ext/ext.dart';
import 'package:enterprise_v6_app/app/core/utils/interface.dart';
import 'package:enterprise_v6_app/app/modules/auth/face/iface.dart';
import 'package:enterprise_v6_app/app/modules/profile/controller.dart';

class HomeMyProfileController extends GetxController {
  final profile = Get.find<HomeMyController>();

  /// 人脸地址
  String faceUrl = '';
  Uint8List? faceData;

  /// 签名笔迹
  final signatureUrl = ''.obs;

  /// 是否允许退出页面
  bool canPop = false;

  @override
  void onInit() {
    super.onInit();
    signatureUrl.value = profile.entity!.signatureUrl;
    faceUrl = profile.entity!.faceUrl;
    Dio()
        .get(
      Interface.fileUrl + faceUrl,
      options: Options(responseType: ResponseType.bytes),
    )
        .then((value) {
      faceData = Uint8List.fromList(value.data as List<int>);
    });
    if (signatureUrl.value.isEmpty || faceUrl.isEmpty) {
      canPop = false;
    } else {
      canPop = true;
    }
  }

  /// 更新信息
  void updateInfo() {
    final signUrl = signatureUrl.value;
    if (signUrl.isNotNullAndNotEmpty && faceUrl.isNotEmpty) {
      profile.entity!.faceUrl = faceUrl;
      profile.entity!.signatureUrl = signUrl;
      updateFace();
    } else {
      AppToast.showWarning('请完善用户信息!');
      return;
    }
    profile.updateProfile();
  }

  /// 更新人脸
  Future<void> updateFace() async {
    if (faceData == null) {
      AppToast.showWarning('无照片数据');
      return;
    }
    await FaceAuthApi.add(base64Encode(faceData!));
  }
}
